#coding=utf-8
#Boa:FramePanel:PanelProduct

import wx

import DlgKeyword
import DlgCustomerChoice
import DlgPopupSupplier

from MyListCtrl import *
from product import *
from ctrlAider import *

[wxID_PANELPRODUCT, wxID_PANELPRODUCTSPLITTER, 
] = [wx.NewId() for _init_ctrls in range(2)]

[TypeSale,TypePurchase,TypeProAll] = [i for i in range(3)]   

class PanelProduct(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELPRODUCT, name=u'PanelProduct',
              parent=prnt, pos=wx.Point(432, 34), size=wx.Size(636, 668),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(628, 634))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,u'Arial'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))

        self.splitter = wx.SplitterWindow(id=wxID_PANELPRODUCTSPLITTER,
              name=u'splitter', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(628, 600), style=wx.SP_3D)
        self.splitter.SetMinimumPaneSize(2)

    def __init__(self, parent, type, peerObj=None, bSelect=True):
        '''bSelect - 是否商品双击选择模式，购销单据选择产品时使用'''
        self._init_ctrls(parent)
                
        self.curType = type
        self.peerObj = peerObj
        self.bSelect = bSelect

        self.myInit()
    
    def myInit(self):
        if not(self.bSelect):
            self.SetSize(self.GetParent().GetClientSize())
            self.splitter.SetSize(self.GetClientSize())
            print self.GetSize()
            print self.GetClientSize()
            print self.splitter.GetSize()
            print self.splitter.GetSize()
            
        self.curKeywords = []
        self.curCategory = None
        
        self.categoryList = MyCategoryTreeCtrl(self.splitter)

        self.categoryList.Bind(wx.EVT_TREE_SEL_CHANGED,
                                self.OnTreeSelChanged)

        self.winRight = wx.Window(self.splitter, style=wx.BORDER_SUNKEN)
        self.initWinRight(self.winRight)
               
        self.splitter.SplitVertically(self.categoryList, self.winRight, 100)
                
    def initWinRight(self, parent):
        listWidth = self.splitter.GetClientSize().GetWidth() - 140
        print listWidth
        
        if(self.curType == TypeProAll):
            self.tKeyword = wx.StaticText(id=-1,
                  label=u'\u641c\u7d22\u6807\u7b7e\uff1a', name='tKeyword',
                  parent=parent, pos=wx.Point(5, 18), size=wx.Size(85, 16),
                  style=0)
                  
            self.btnKeyword = wx.lib.buttons.GenButton(id=-1,
                  label=u'点击选择搜索标签', name=u'btnKeyword', parent=parent,
                  pos=wx.Point(90, 10), size=wx.Size(304, 24), style=0)
            self.btnKeyword.Bind(wx.EVT_BUTTON, self.OnBtnKeywordButton)
            
            self.btnRmLabel = wx.Button(id=-1,
                  label=u'清除标签', name=u'btnRmLabel', parent=parent,
                  pos=wx.Point(400, 10), size=wx.Size(93, 24), style=0)
            self.btnRmLabel.Bind(wx.EVT_BUTTON, self.OnBtnRmLabelButton)
            
            self.chkShowUnused = wx.CheckBox(id=-1,
                  label=u'显示禁用商品', parent=parent,
                  pos=wx.Point(550, 10))
            self.chkShowUnused.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxShowUnused)
                    
            self.tSearch = wx.StaticText(id=-1,
                  label=u'\u641c\u7d22\uff1a', name=u'tSearch', parent=parent,
                  pos=wx.Point(5, 50), size=wx.Size(51, 16), style=0)

            self.tcSearch = wx.TextCtrl(id=-1, name=u'tcSearch',
                  parent=parent, pos=wx.Point(90, 42), size=wx.Size(120, 26),
                  style=wx.TE_PROCESS_ENTER, value=u'')
            self.tcSearch.Bind(wx.EVT_TEXT_ENTER, self.OnTcSearchTextEnter)

            self.btnSearch = wx.Button(id=-1,
                  label=u'\u641c\u7d22', name=u'btnSearch', parent=parent,
                  pos=wx.Point(220, 42), size=wx.Size(93, 26), style=0)
            self.btnSearch.Bind(wx.EVT_BUTTON, self.OnBtnSearchButton)

            self.btnAddLabel = wx.Button(id=-1,
                  label=u'\u6dfb\u52a0\u5230\u641c\u7d22\u6807\u7b7e',
                  name=u'btnAddLabel', parent=parent, pos=wx.Point(320, 42),
                  size=wx.Size(144, 26), style=0)
            self.btnAddLabel.Bind(wx.EVT_BUTTON, self.OnBtnAddLabelButton)
            
            self.proList = MyProductListCtrl(parent)
            self.proList.SetSize(wx.Size(490, 475))
            self.proList.Move(wx.Point(10, 80))
            self.proList.refresh()
            
            if not(self.bSelect):
                pass
                
        else:
            self.tPeer = wx.StaticText(id=-1,
                label=u'客户名称：', name=u'tPeer',
                parent=parent, pos=wx.Point(10, 32), size=wx.Size(90, 24), style=0)

            self.tcPeerName = wx.TextCtrl(id=-1,
                  name=u'tcPeerName', parent=parent, pos=wx.Point(100, 24),
                  size=wx.Size(248, 28), style=0, value=u'')
            
            self.btnShowPeer = wx.Button(id=-1, label=u'+',
                  name=u'btnShowPeer', parent=parent, pos=wx.Point(348, 24),
                  size=wx.Size(24, 29), style=0)
            self.btnShowPeer.Bind(wx.EVT_BUTTON, self.OnBtnShowPeerButton)
                    
            self.btnSelectPeer = wx.Button(id=-1,
                  label=u'\u67e5\u627e', name=u'btnSelectPeer', parent=parent,
                  pos=wx.Point(380, 24), size=wx.Size(80, 29), style=0)
            self.btnSelectPeer.Bind(wx.EVT_BUTTON, self.OnBtnSelectPeerButton)
                
            if (self.curType == TypeSale):                
                self.popupWin = DlgCustomerChoice.create(self)
                self.tcPeer = MyPopupTextCtrlDecorator(self.tcPeerName, self.popupWin)

                self.proList = MyListCtrlCustProRecent(parent)
                
                if (self.peerObj is not None):
                    self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
                    self.tcPeer.ChangeValue(self.peerObj.getValue(self.peerObj.COL_NAME))
                
                self.lcDetail = MyListCtrlProSaleDetail(parent)
                
            elif (self.curType == TypePurchase):
                self.tPeer.SetLabel(u'供货商名称')
                self.popupWin = DlgPopupSupplier.create(self)
                self.tcPeer = MyPopupTextCtrlDecorator(self.tcPeerName, self.popupWin)
                
                self.proList = MyListCtrlSupplierProRecent(parent)
##                self.proList.SetSize(wx.Size(listWidth, 265))
##                self.proList.Move(wx.Point(10, 80))
##                self.proList.setViewProSelect()
##                self.proList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnPurItemSelected)
                
                if (self.peerObj is not None):
                    self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
                    self.tcPeer.ChangeValue(self.peerObj.getValue(self.peerObj.COL_NAME))
                
                self.lcDetail = MyListCtrlProPurDetail(parent)
##                self.lcPurDetail.SetSize(wx.Size(listWidth, 200))
##                self.lcPurDetail.Move(wx.Point(10, 355))
##                self.lcPurDetail.setViewProSelect()
                
            self.proList.SetSize(wx.Size(listWidth, 265))
            self.proList.Move(wx.Point(10, 65))
            self.proList.setViewProSelect()
            self.proList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSaleItemSelected) 
            
            self.lcDetail.SetSize(wx.Size(listWidth, 200))
            self.lcDetail.Move(wx.Point(10, 340))
            self.lcDetail.setViewProSelect()
                 
        #self.proList = self.getListCtrl(parent)
        if(self.bSelect):
            self.proList.Bind(wx.EVT_LEFT_DCLICK, self.OnProListLeftDclick)
    
    def setViewTypeProAll(self, type):
        '''只是针对TypeProAll中的列显示起作用''' 
        self.typeAll_state = type
        if (type == TypeSale):
            self.proList.setViewProSelect(self.proList.viewSale)
        elif (type == TypePurchase):
            self.proList.setViewProSelect(self.proList.viewPur)
        elif (type == TypeProAll):
            #self.proList.Unbind(wx.EVT_LEFT_DCLICK)
            self.proList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnProAllItemSelected)
            self.SetSize(self.GetParent().GetClientSize())
            self.splitter.SetSize(self.GetParent().GetClientSize())
            self.proList.SetSize(wx.Size(1050,265))
            
            self.lcPurDetail = MyListCtrlProPurDetail(self.winRight)
            self.lcPurDetail.SetSize(wx.Size(520, 220))
            self.lcPurDetail.Move(wx.Point(10, 355))
            #self.lcPurDetail.setViewProSelect()
            
            self.lcSaleDetail = MyListCtrlProSaleDetail(self.winRight)
            self.lcSaleDetail.SetSize(wx.Size(520, 220))
            self.lcSaleDetail.Move(wx.Point(540, 355))
            #self.lcSaleDetail.setViewProSelect()
            
##    def getListCtrl(self, parent):
##        if (self.curType == TypeProAll):
##            lc = MyProductListCtrl(parent)
##            lc.SetSize(wx.Size(490, 475))
##            lc.Move(wx.Point(10, 80))
##            lc.refresh()
##            
##        elif (self.curType == TypeSale):
##            lc = MyListCtrlCustProRecent(parent)
##            lc.SetSize(wx.Size(490, 265))
##            lc.Move(wx.Point(10, 80))
##            lc.setViewProSelect()
##            if (self.peerObj is not None):
##                lc.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
##            
##            lc.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSaleItemSelected)
##            
##            self.lcSaleDetail = MyListCtrlProSaleDetail(parent)
##            self.lcSaleDetail.SetSize(wx.Size(490, 200))
##            self.lcSaleDetail.Move(wx.Point(10, 355))
##            self.lcSaleDetail.setViewProSelect()
##            
##        elif (self.curType == TypePurchase):
##            lc = MyListCtrlSupplierProRecent(parent)
##            lc.SetSize(wx.Size(490, 265))
##            lc.Move(wx.Point(10, 80))
##            lc.setViewProSelect()
##            if (self.peerObj is not None):
##                lc.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
##            lc.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnPurItemSelected)
##            
##            self.lcPurDetail = MyListCtrlProPurDetail(parent)
##            self.lcPurDetail.SetSize(wx.Size(490, 200))
##            self.lcPurDetail.Move(wx.Point(10, 355))
##            self.lcPurDetail.setViewProSelect()
##            
##        else:
##            return None
##        
##        return lc
    
    def refreshProductList(self):
        '''根据搜索条件（类别、关键字），重设产品列表'''
        categoryIds = []
        if (self.curCategory is not None):
            categoryId = self.curCategory.getFieldVal(index=CDataCategory.COL_ID)
            categoryIds = CDataCategory.getChildId(categoryId)
        
        keywordIds = []
        for obj in self.curKeywords:
            keywordIds.append(obj.getFieldVal(index=CDataKeyword.COL_ID))
        
        #重设产品
        self.proList.setFilter(keywordIds, categoryIds)
        if (self.curType == TypeProAll):
            self.proList.refresh()
        elif (self.curType == TypeSale):
            if(self.peerObj is not None):
                self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
        elif (self.curType == TypePurchase):
            if(self.peerObj is not None):
                self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
            
    def appendProDetail(self, data):
        '''data - ([proId,proName,unit,cnt,price,amount], )'''
        # 注意接收端参数是二维列表
        self.GetGrandParent().appendProDetail(data)
    
    def setSelectObj(self, obj):
        '''设置选中客户'''
        if (obj is not None):
            #if None, we keep old value
            self.peerObj = obj
            
        if (self.peerObj is not None):
            name = self.peerObj.getValue(self.peerObj.COL_NAME)
            self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})
        else:
            name = ''
            
        self.tcPeer.ChangeValue(name)
        
        
    def setCustomer(self, obj):
        '''设置选中客户'''
        self.setSelectObj(obj)
    
    def getSelectPeer(self):
        return self.peerObj
    
    def setSelectPeer(self, obj):
        self.setSelectObj(obj)
    
    def clearSelectPeer(self):
        self.tcPeer.ChangeValue('')
        self.proList.DeleteAllItems()
        self.lcDetail.DeleteAllItems()
        
    def OnBtnSelectPeerButton(self, event):
        if self.tcPeer.GetValue() == '':
            self.peerObj = None
        
        if (self.peerObj is not None):
            self.proList.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID)})

        
    def OnProAllItemSelected(self, event):
        '''产品列表被选择，显示产品的采购与销售历史'''
        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        proId = int(self.proList.GetItem(item, self.proList.iId).GetText())
        self.lcPurDetail.refresh({'proId':proId})
        self.lcSaleDetail.refresh({'proId':proId})                        
                                
    
    def OnPurItemSelected(self, event):
        '''采购历史页面，产品被选择后显示产品采购历史'''
        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        proId = int(self.proList.GetItem(item, self.proList.iProId).GetText())
        self.lcDetail.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID),
                                'proId':proId})
    
    def OnSaleItemSelected(self, event):
        '''采购历史页面，产品被选择后显示产品采购历史'''
        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        proId = int(self.proList.GetItem(item, self.proList.iProId).GetText())
        self.lcDetail.refresh({'peerId':self.peerObj.getValue(self.peerObj.COL_ID),
                                'proId':proId})
                                    
    def OnBtnRmLabelButton(self, event):
        self.btnKeyword.SetLabel(u'点击选择搜索标签')
        self.curKeywords = []
        self.refreshProductList()
        # 140808 以下代码是为了触发btnKeyword刷新显示
        self.btnKeyword.SetFocus()
           
    def OnTreeSelChanged(self, event):
        self.curCategory = self.categoryList.getSelection()
        self.refreshProductList()        
        event.Skip()

    def OnBtnKeywordButton(self, event):
        
        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()
        
        dlg = DlgKeyword.create(self)
        dlg.setData(self.curKeywords)
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return
        
##        import DlgProLabel
##        dlg = DlgProLabel.create(self)
##        if (dlg.ShowModal() == wx.ID_CANCEL):
##            return
        
        self.curKeywords = dlg.keywordSel
        str = ''
        for obj in self.curKeywords:
            str += '%s  ' %obj.getFieldVal(index=CDataKeyword.COL_NAME)
        btn.SetLabel(str)
        #btn.SetSize(btn.GetBestSize())
        self.refreshProductList()
        
    def OnProListLeftDclick(self, event):
        '''左键双击产品列表,弹出产品数量、价格窗口'''
        import DlgProGX
##        obj = self.proList.getSelectObj()
##        if (obj == None):
##            print '[Error]unknown product: %s' %(fields)

        item = self.proList.GetNextItem(-1, state = wx.LIST_STATE_SELECTED)
        if (item == -1):
            return
            
        proId,proName,proSpec,unit,price = self.proList.getProSaleInfo(item)
        dlg = DlgProGX.create(self.GetGrandParent())
        dlg.setData(proId=proId, unit=unit, price=price)
        
        if (self.curType == TypeSale):
            dlg.setInbound(False)
        elif (self.curType == TypeProAll):
            if (self.typeAll_state == TypeSale):
                dlg.setInbound(False)
            elif (self.typeAll_state == TypeProAll):
                kit.showModal(u'异常状态：TypeALL')
        
        
        if (dlg.ShowModal() == wx.ID_OK):
            data = []
            data.append([str(proId), proName, proSpec,dlg.unit,
                        str(dlg.cnt), str(dlg.price), str(dlg.cnt*dlg.price)])
            
            for unit,cnt in dlg.lonelyUnit.items():
                data.append([str(proId), proName, proSpec,unit, str(cnt), 0.0, 0.0])
                
            self.appendProDetail(data)

    def refreshList(self, val):
        #print val
        if (val == ''):
            self.proList.refresh()
        else:
            self.proList.refreshView(val)
        
    def OnBtnSearchButton(self, event):
        self.refreshList(self.tcSearch.GetValue())

    def OnTcSearchTextEnter(self, event):
        self.btnSearch.SetFocus()
        self.refreshList(self.tcSearch.GetValue())

    def OnBtnAddLabelButton(self, event):
        '''把搜索内容设置为label，并关联到列表中的显示项目'''
        if (self.tcSearch.GetValue() == ''):
            dlg = wx.MessageDialog(self, u'没有设置标签',u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            return

        # 此处允许重复操作
        labelId = CDataKeyword.add(self.tcSearch.GetValue())
        if(labelId == -1):
            dlg = wx.MessageDialog(self, u'添加标签发生错误',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        for row in range(self.proList.GetItemCount()):
            proObj = self.proList.getObj(row)
            proObj.attachLabel(labelId)
            
        msg = u'该列表中的商品已经关联到标签<%s>，可以在搜索标签中直接选择' %self.tcSearch.GetValue()
        dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_ERROR)
        dlg.ShowModal()
        
##            obj = CDataProLabel()
##            fields = {CDataProLabel.COL_PROID:self.proList.getProId(row),
##                        CDataProLabel.COL_LABELID:labelId}
##            obj.setMulFieldVal(fields)
##            obj.insert()
            
    def OnBtnShowPeerButton(self, event):
        self.tcPeer.resetPopupWinPos()
        self.popupWin.Show()
        event.Skip()
        
    def OnCheckBoxShowUnused(self, event):
        self.proList.setShowUnused(self.chkShowUnused.GetValue())
        self.proList.refresh()
